package com.mmdccj.yugu.controller;

import com.mmdccj.yugu.common.Result;
import com.mmdccj.yugu.entity.MusicList;
import com.mmdccj.yugu.entity.SocialInfo;
import com.mmdccj.yugu.entity.User;
import com.mmdccj.yugu.service.MusicListService;
import com.mmdccj.yugu.service.SocialInfoService;
import com.mmdccj.yugu.service.UserService;
import com.mmdccj.yugu.utils.MD5Util;
import com.mmdccj.yugu.utils.SnowFlakeUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: star_
 * @date: 2023-11-25 17:24
 */
@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MusicListService musicListService;
    @Autowired
    private SocialInfoService socialInfoService;

    /**
     * 用户登录
     *
     * @param request 请求
     * @param user    用户
     * @return Result<String>
     */
    @PostMapping("/login/account")
    public Result<String> accountLogin(HttpServletRequest request, @RequestBody User user) {
        log.info("普通用户账户登录...");
        // 对密码进行MD5加密
        String password = MD5Util.getMD5(user.getPassword());
        User selectUser = userService.getUserByAccount(user.getAccount());

        if (selectUser == null) {
            return Result.error("该账户未注册");
        } else if (!selectUser.getPassword().equals(password)) {
            return Result.error("密码错误");
        }

        // 将用户id存入session
        request.getSession().setAttribute("user", selectUser.getId());
        System.out.println(request.getSession().getAttribute("user"));
        log.info("用户 {} 登录了...", user.getAccount());
        return Result.success("成功登录", null);
    }

    /**
     * 根据邮箱查询用户
     *
     * @param request 请求
     * @param user    用户
     * @return Result<String>
     */
    @PostMapping("/login/email")
    public Result<String> emailLogin(HttpServletRequest request, @RequestBody User user) {
        log.info("普通用户邮箱登录...");
        // 对密码进行MD5加密
        String password = MD5Util.getMD5(user.getPassword());

        User selectUser = userService.getUserByEmail(user.getEmail());

        if (selectUser == null) {
            return Result.error("该账户未注册");
        } else if (!selectUser.getPassword().equals(password)) {
            return Result.error("密码错误");
        }

        // 将用户id存入session
        request.getSession().setAttribute("user", selectUser.getId());

        log.info("用户 {} 登录了...", user.getAccount());
        return Result.success("成功登录", null);
    }

    /***
     * 注册检查用
     *
     * @param account 用户名
     * @return Result<String>
     */
    @GetMapping("/login/checkAccount")
    public Result<String> checkAccount(String account) {
        if (userService.isUser(account)) {
            return Result.error("已经存在的用户名");
        } else {
            return Result.success("未被注册的用户名");
        }
    }

    @GetMapping("/register/checkPhone")
    public Result<String> checkPhone(String phone) {
        if (userService.isPhone(phone)) {
            return Result.error("已经存在的号码");
        } else {
            return Result.success("未被注册的号码");
        }
    }

    /**
     * 用户注册
     *
     * @param user 用户
     * @return Result<String>
     */

    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        log.info("普通用户注册...");
        // 查询有无重复
        User selectUser = userService.getUserByAccount(user.getAccount());
        if (selectUser != null) {
            return Result.success("该用户已注册");
        }
        // 使用雪花算法生成用户id
        user.setId(SnowFlakeUtil.getSnowFlakeId().toString());

        // 对密码进行加密
        user.setPassword(MD5Util.getMD5(user.getPassword()));

        // 设置基础属性
        user.setType("U");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 将用户的数据插入到数据库
        userService.insertUser(user);

        log.info("用户 {} 注册了...", user.getAccount());
        return Result.success("成功注册");
    }

    /**
     * 获取用户信息
     *
     * @param request request对象
     * @param account 账号
     * @return Result<User>
     */
    @GetMapping("/info")
    public Result<User> info(HttpServletRequest request, String account) {
        User user;
        if (account.equals("")) {
            String sessionId = (String) request.getSession().getAttribute("user");
            log.info("session用户id{}", sessionId);
            user = userService.getUserById(sessionId);
        } else {
            log.info("获取用户{}", account);
            user = userService.getUserByAccount(account);
        }
        user.setPassword(null);
        return Result.success("成功获取用户信息", user);
    }

    /**
     * 根据用户id获取用户社交信息
     *
     * @param id 用户信息
     * @return Result<SocialInfo> 返回社交信息
     */
    @GetMapping("/socialInfo")
    public Result<SocialInfo> socialInfo(String id) {
        return Result.success("成功", socialInfoService.getSocialInfoByUserId(id));
    }

    /**
     * 退出登录
     *
     * @param request 请求
     * @return Result<String>
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return Result.success("注销成功");
    }

    /**
     * 通过歌曲id获取歌手信息
     *
     * @param musicId 歌曲id
     * @return Result<User> 歌手信息
     */
    @GetMapping("/getSingerInfo")
    public Result<User> getSingerInfo(String musicId) {
        if (musicId == null) {
            return Result.error("参数为空");
        }
        User user = userService.getUserByMusicId(musicId);
        if (user == null) {
            return Result.error("错误的音乐id");
        }
        return Result.success("成功", user);
    }

    /**
     * 通过session中的用户id 或 传来的id 获取用户创建的歌单
     *
     * @param session 用户session
     * @param userId  用户id
     * @return Result<List < MusicList>> 结果
     */
    @GetMapping("/getMyMusicList")
    public Result<List<MusicList>> getMyMusicList(HttpSession session, String userId) {
        String id;
        if (userId != null) {
            id = userId;
        } else {
            if (session.getAttribute("user") == null) {
                return Result.error("未登录");
            } else {
                id = (String) session.getAttribute("user");
            }
        }
        List<MusicList> musicList = musicListService.getMusicListByUserId(id);
        if (musicList == null) {
            return Result.error("错误的用户id,或者用户未创建歌单");
        }
        return Result.success("成功", musicList);
    }

    /**
     * 通过session更新相应用户的信息
     *
     * @param session   session
     * @param introduce 简介
     * @param nickName  昵称
     * @return Result<String> 结果
     */
    @PostMapping("/updateUserInfo")
    public Result<String> updateUserInfo(HttpSession session, String introduce, String nickName) {
        String id = (String) session.getAttribute("user");
        if (userService.updateUserInfo(id, nickName, introduce)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 获取用户公开信息
     *
     * @param userId 用户id
     * @return Result<User> 用户信息
     */
    @GetMapping("/getPublicInfo")
    public Result<User> getPublicInfo(String userId) {
        if (userId == null) {
            return Result.error("缺少参数");
        }
        return Result.success("成功", userService.getPublicUserInfo(userId));
    }

    /**
     * 获取用户头像
     *
     * @param session session
     * @return Result<String>
     */
    @GetMapping("/avatar")
    public Result<String> getAvatar(HttpSession session) {
        String id = (String) session.getAttribute("user");
        if (id == null) {
            return Result.error("未登录");
        } else {
            return Result.success("成功", userService.getAvatar(id));
        }
    }

    /**
     * 更新用户头像信息
     *
     * @param session session
     * @param avatar  头像文件名称
     * @return Result<String> 结果
     */
    @PostMapping("/updateAvatar")
    public Result<String> updateAvatar(HttpSession session, String avatar) {
        String id = (String) session.getAttribute("user");
        if (id == null) {
            return Result.error("未登录");
        } else {
            if (userService.updateAvatar(id, avatar)) {
                return Result.success("成功");
            } else {
                return Result.error("失败");
            }
        }
    }

    /**
     * 获取收藏该歌单的最多8个用户
     *
     * @param musicListId 歌单id
     * @return Result<List < User>>
     */
    @GetMapping("/getCollectUsers")
    public Result<List<User>> getCollectUsers(String musicListId) {
        if (musicListId == null) {
            return Result.error("参数缺失");
        }
        List<User> users = userService.getCollectUsers(musicListId);
        if (users != null) {
            return Result.success("成功获取收藏该歌单用户", users);
        } else {
            return Result.success("还没有用户收藏该歌单");
        }
    }
}
